package fun.coding.leetcode;

public class SwapNodesInPairs {

	public static void main(String[] args) {
		SwapNodesInPairs instance = new SwapNodesInPairs();
		
		int[] a1 = {1, 2, 3, 4};
		ListNode l1 = LeetCodeHelpers.buildLinkedList(a1);
		ListNode l1Res = instance.swapPairs(l1);
		LeetCodeHelpers.printList(l1Res);
		
		int[] a2 = {1, 2, 3};
		ListNode l2 = LeetCodeHelpers.buildLinkedList(a2);
		ListNode l2Res = instance.swapPairs(l2);
		LeetCodeHelpers.printList(l2Res);
	}
	
	// Should also try recursion. but that uses extra spaces
	// Dummy with 2 pointers
	public ListNode swapPairs(ListNode head) {
		if (head == null) return null;
		
		ListNode dummyHead = new ListNode(-1);
		dummyHead.next = head;
		
		ListNode cur = dummyHead;
		ListNode next = cur.next;
		
		while (next != null && next.next != null) {
			cur.next = next.next;
			cur = next;
			ListNode t = next.next.next;
			next.next.next = next;
			cur.next = t;
			next = cur.next;
		}
		
		return dummyHead.next;
	}

}
